<?php 
class kdtrace_urgent extends Controller {
	
	function track( $tracknum  , $lang = ""){

		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "http://183.129.132.4:8000/express/exptrn.do?theAction=searchWorld&keyword=" . $tracknum);
        curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Referer: http://183.129.132.4:8000/',
			'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36' 
		));
		$result = curl_exec($ch);
        curl_close($ch);

		$rtndata = array('tracknum'=>$tracknum,'header'=>array(),'err'=>array(),'eventList'=>array());
		$result = $this->skipSpaces($result);
		$result = mb_convert_encoding($result ,"UTF-8","GB2312");
		
		$w1 = strpos($result , '<div class="textcontent">');
		$w2 = strpos($result , "</div>" , $w1);
		$rhtm = substr($result , $w1 , $w2-$w1);
		
		if(preg_match("/>目的地\[Destinations\]<\/td><td>(.+?)<\/td>/i", $rhtm, $matches) >0){
			$rtndata['header']['shipTo']		= $matches[1];
		};
		if(preg_match("/>签收人<\/td><td>(.+?)<\/td>/i", $rhtm, $matches) >0){
			$rtndata['header']['SignedBy']		= $matches[1];
			trim($matches[1])!="" ? $rtndata['header']['isDelivered']=true : $rtndata['header']['isDelivered']=false;
		};

		$w1 = strpos($rhtm , '<b>状态</b><');
		$w2 = strpos($rhtm , "</table>" , $w1);
		$bdhtm = substr($rhtm , $w1 , $w2-$w1);
		preg_match_all("/<td width\=\"20%\">(.+?)<\/td><td width\=\"20%\">(.+?)<\/td><td width\=\"30%\">(.+?)<\/td><td width\=\"30%\">(.+?)<\/td>/i" , $bdhtm , $matches);
		$count = count($matches[0]);
		if($count>0){
			for($i=0 ; $i < $count ; $i++){
				//$this->skipSpaces($matches[1][$i])
				$tt =  strtotime( strip_tags($matches[1][$i]) . " " . strip_tags($matches[2][$i]) );
				$rtndata['eventList'][$i] = array(
					"date"			=> date('Y-m-d',$tt),
					"time"			=> date('h:i:s',$tt),
					"utime"			=> $tt,
					"status"		=> trim(strip_tags($matches[4][$i])),
					"location"		=> trim(strip_tags($matches[3][$i]))
				);
			}
		}

		$rtndata['eventList'] = array_reverse( $rtndata['eventList'] );
		return $rtndata;

	}
	function skipSpaces($t){
			return  trim(preg_replace('/\s{2,}/', ' ', $t));
	}
	
	function str_format_time($times){
		if(preg_match("/^(.+?)\/(.+?)\/(.+?) (.+?):(.+?)$/i" , $times , $matchs)){
			$timestamp = mktime($matchs[4] , $matchs[5] , 0, $matchs[2], $matchs[1], $matchs[3]);
		}
		return $timestamp;
	}
}
?>